package resp

import (
	"gamers/pkg/errorcode"
	"os"

	"github.com/gin-gonic/gin"
)

// Response 标准返回
type Response struct {
	Code      int         `json:"code"`
	Msg       interface{} `json:"msg"`
	Data      interface{} `json:"data,omitempty"`
	TraceHost string      `json:"hostname"`
}

// PageDataResponse 分页数据处理返回
type PageDataResponse struct {
	Count  int64       `json:"count"`
	Offset int         `json:"offset"`
	Limit  int         `json:"limit"`
	List   interface{} `json:"list,omitempty"`
}

// RespSuccess 默认成功返回格式
func RespSuccess(c *gin.Context, data interface{}) {
	hostname, _ := os.Hostname()
	if data == nil {
		c.JSON(200, &Response{
			Code:      200,
			Msg:       "请求成功",
			TraceHost: hostname,
		})
	} else {
		c.JSON(200, &Response{
			Code:      200,
			Msg:       "请求成功",
			Data:      data,
			TraceHost: hostname,
		})
	}
}

// ToErrorResponse 错误返回
func ToErrorResponse(ctx *gin.Context, code int, err *errorcode.Error) {
	response := gin.H{"code": err.Code(), "msg": err.Msg()}
	ctx.JSON(code, response)
}

// PagedDataSuccess 分页数据返回处理
func PagedDataSuccess(c *gin.Context, code int, data interface{}, Count int64, Offset int, Limit int) {
	c.JSON(200, &Response{
		Code: code,
		Msg:  "请求成功",
		Data: &PageDataResponse{
			Count:  Count,
			Offset: Offset,
			Limit:  Limit,
			List:   data,
		},
	})
}
